import { FishModeState, EditorConfig, InputEvent } from '../types/editor';
import { NovelService } from './novelService';
import { WordHelper } from '../utils/wordHelper';

export class FishModeService {
  private static instance: FishModeService;
  private state: FishModeState;
  private config: EditorConfig;
  private novelService: NovelService;
  private lastInputTime: number = 0;
  private inputBuffer: string = '';
  private isProcessing: boolean = false;

  private constructor() {
    this.state = {
      isActive: false,
      currentNovelIndex: 0,
      totalCharacters: 0,
      readCharacters: 0
    };

    this.config = {
      fishModeEnabled: true,
      shortcutKey: 'Ctrl+Shift+F',
      replacementDelay: 100
    };

    this.novelService = new NovelService();
    this.initializeEventListeners();
  }

  public static getInstance(): FishModeService {
    if (!FishModeService.instance) {
      FishModeService.instance = new FishModeService();
    }
    return FishModeService.instance;
  }

  public async initialize(): Promise<void> {
    await this.novelService.loadDefaultNovel();
    this.updateState();
    console.log('FishMode initialized');
  }

  public toggleFishMode(): boolean {
    this.state.isActive = !this.state.isActive;
    console.log(`Fish mode ${this.state.isActive ? 'enabled' : 'disabled'}`);
    
    if (this.state.isActive) {
      this.startFishMode();
    } else {
      this.stopFishMode();
    }

    return this.state.isActive;
  }

  public isFishModeActive(): boolean {
    return this.state.isActive;
  }

  public getState(): FishModeState {
    return { ...this.state };
  }

  private async startFishMode(): Promise<void> {
    try {
      await this.setupWordEventListeners();
      await this.showModeIndicator('摸鱼模式已启用');
    } catch (error) {
      console.error('Failed to start fish mode:', error);
      this.state.isActive = false;
    }
  }

  private async stopFishMode(): Promise<void> {
    try {
      await this.showModeIndicator('正常模式已启用');
    } catch (error) {
      console.error('Failed to stop fish mode:', error);
    }
  }

  private async setupWordEventListeners(): Promise<void> {
    try {
      await Word.run(async (context) => {
        // 注册键盘事件监听，而不是文档事件
        // Word插件中直接监听键盘事件效果更好
        console.log('Word event listeners setup completed');
        await context.sync();
      });
    } catch (error) {
      console.error('Failed to setup Word event listeners:', error);
      throw error;
    }
  }

  // 改为直接处理用户输入的方法
  public async processUserInput(inputChar: string): Promise<string> {
    if (!this.state.isActive) return inputChar;
    
    const novelChar = this.novelService.getNextCharacter();
    if (novelChar) {
      this.updateReadProgress();
      return novelChar;
    }
    
    return inputChar;
  }

  private updateReadProgress(): void {
    const progress = this.novelService.getProgress();
    if (progress) {
      this.state.readCharacters = progress.position;
      this.state.totalCharacters = this.novelService.getCurrentNovel()?.totalLength || 0;
    }
  }

  private updateState(): void {
    const currentNovel = this.novelService.getCurrentNovel();
    if (currentNovel) {
      this.state.totalCharacters = currentNovel.totalLength;
      this.state.readCharacters = currentNovel.currentPosition;
    }
  }

  private async showModeIndicator(message: string): Promise<void> {
    try {
      console.log(message);
    } catch (error) {
      console.error('Error showing mode indicator:', error);
    }
  }

  private initializeEventListeners(): void {
    if (typeof window !== 'undefined') {
      window.addEventListener('keydown', (event) => {
        if (event.ctrlKey && event.shiftKey && event.key === 'F') {
          event.preventDefault();
          this.toggleFishMode();
        }
      });
    }
  }

  public getNovelService(): NovelService {
    return this.novelService;
  }

  public async reset(): Promise<void> {
    this.state.isActive = false;
    this.state.readCharacters = 0;
    this.novelService.resetProgress();
    this.updateState();
  }
}